package cn.com.backstage.controller;

import java.awt.Color;
import java.awt.Font;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspWriter;

import org.apache.log4j.Logger;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.ValueMarker;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.RectangleAnchor;
import org.jfree.ui.TextAnchor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.com.api.service.ApiT_log_userService;
import cn.com.api.entity.*;
import cn.com.util.*;

@Controller
@RequestMapping(Utils.SYS_BACKSTAGE+"/")
public class T_log_userController {

	private static Logger logger = Logger.getLogger(T_log_userController.class);
	@Autowired
	private ApiT_log_userService apiT_log_userService;
	
	/**
	 * 销量报表
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "t_log_user_goodsSaleStatistics")
	public void goodsSaleStatistics(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		ModelAndView mv = new ModelAndView("forward:/backstage/t_log_user_goodssale_stats_all.jsp");
		
		List<String> yearList = apiT_log_userService.getYearList();
		List<String> monthList = apiT_log_userService.getMonthList("2016");
		List<String> dayList = apiT_log_userService.getDayList("2016", "02");
		
		mv.addObject("yearList", yearList);
		
//		return mv;
	}
	
	/**
	 * 销量报表-按月统计-根据年
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "t_log_user_goodsSale_year")
	public void goodsSaleYear(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		ModelAndView mv = new ModelAndView("forward:/backstage/t_log_user_goodssale_stats_year.jsp");
		
		List<String> yearList = apiT_log_userService.getYearList();
		List<String> monthList = apiT_log_userService.getMonthList("2016");
		List<String> dayList = apiT_log_userService.getDayList("2016", "02");
		
		mv.addObject("yearList", yearList);
		
//		return mv;
	}
	
	/**
	 * 商品排行榜
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "t_log_user_goodsRank")
	public ModelAndView t_log_user_goodsRank(HttpServletRequest request,
			HttpServletResponse response,PageInfo pageInfo) throws Exception{
		ModelAndView mv = new ModelAndView("forward:/backstage/t_log_user_goods_rank.jsp");
		//根据日期查询--按销量排序
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		Map<String,Object> conditions = new HashMap<String,Object>();
		conditions.put("startDate", startDate);
		conditions.put("endDate", endDate);
		conditions.put("sort", "sold");
		List<Goods_Sale_List> goodsList = apiT_log_userService.getGoodsRankByDate(conditions, pageInfo);
		
		mv.addObject("goodsList", goodsList);
		mv.addObject("pageInfo", pageInfo);
		mv.addObject("conditions", conditions);
		
		return mv;
	}
	
	/**
	 * 商品转化率
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "t_log_user_goodsTransformationRate")
	public ModelAndView t_log_user_goodsTransformationRate(HttpServletRequest request,
			HttpServletResponse response,PageInfo pageInfo) throws Exception{
		ModelAndView mv = new ModelAndView("forward:/backstage/t_log_user_goods_rate.jsp");
		//根据日期查询--按转化率排序
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		Map<String,Object> conditions = new HashMap<String,Object>();
		conditions.put("startDate", startDate);
		conditions.put("endDate", endDate);
		conditions.put("sort", "rate");
		List<Goods_Sale_List> goodsList = apiT_log_userService.getGoodsRankByDate(conditions, pageInfo);
		
		mv.addObject("goodsList", goodsList);
		mv.addObject("pageInfo", pageInfo);
		mv.addObject("conditions", conditions);
		
		return mv;
	}
	
	public String getGoodsSaleStatsFileName(HttpSession session ,JspWriter out){
		String filename=null;
        double []xydata1_0={12.8d,12.3d,12.9d,12.2d,13.3d,12.0d,12.8d,13.3d,12.9d,13.9d,12.3d,12.0d,12.8d,12.3d,11.9d,13.2d,12.3d,14.0d,12.8d,12.3d,12.9d,13.2d,13.3d,14.0d,12.8d,13.3d,11.9d,13.9d,12.3d,12.0d,19.8d,12.3d,14.9d,18.2d,12.3d,14.0d,12.8d,12.3d,12.9d,18.2d,13.3d,14.0d,12.8d,14.3d,12.9d,13.9d,12.3d,12.0d,13.8d,12.3d,11.9d,13.2d,12.3d,14.0d,12.8d,12.3d,12.9d,18.2d,16.3d,18.0d,12.8d,12.3d,19.9d,13.9d,12.3d,12.0d,12.8d,12.3d,12.9d,13.2d,12.3d,14.0d,12.8d,12.3d,12.9d,12.2d,13.3d,12.0d,12.8d,13.3d,12.9d,13.9d};
        double []xydata1_1={196.0d,223.0d,230.5d,241.0d,195.8d,200.3d,200.0d,230.0d,243.5d,261.0d,259.8d,245.3d,236.0d,260.0d,225.5d,230.0d,190.8d,205.3d,196.0d,223.0d,230.5d,241.0d,195.8d,200.3d,200.0d,230.0d,243.5d,261.0d,259.8d,245.3d,236.0d,260.0d,225.5d,230.0d,190.8d,205.3d,196.0d,223.0d,230.5d,241.0d,195.8d,200.3d,200.0d,230.0d,243.5d,261.0d,259.8d,245.3d,236.0d,260.0d,225.5d,230.0d,190.8d,205.3d,196.0d,223.0d,230.5d,241.0d,195.8d,200.3d,200.0d,230.0d,243.5d,261.0d,259.8d,245.3d,236.0d,260.0d,225.5d,230.0d,190.8d,205.3d,196.0d,223.0d,230.5d,241.0d,195.8d,200.3d,200.0d,230.0d,243.5d,261.0d};
        
        XYSeriesCollection xyCollection=new XYSeriesCollection();
        XYSeries xyseries1=new XYSeries("ACompany");
        for(int i=0;i<82;i++){
            xyseries1.add(xydata1_0[i], xydata1_1[i]);
        }
        XYSeries xyseries2=new XYSeries("BCompany");
        
        xyCollection.addSeries(xyseries1);
        
        //分布点状图
        JFreeChart chart=ChartFactory.createScatterPlot("电压电流图", "电流","电压", xyCollection, PlotOrientation.VERTICAL, true, false, false);
        XYPlot plot=(XYPlot) chart.getPlot();
        
        ValueMarker vmarker=new ValueMarker(230d);//设置分割线
        vmarker.setLabel("平均电压230V");
        vmarker.setLabelPaint(Color.black);
        vmarker.setPaint(Color.red);
        vmarker.setLabelFont(new Font("隶书",Font.PLAIN,10));
        vmarker.setLabelAnchor(RectangleAnchor.BOTTOM_RIGHT);
        vmarker.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        plot.addRangeMarker(vmarker);
        
        ValueMarker xMarker=new ValueMarker(12.50d);
        xMarker.setLabel("平均电流12.50A");
        xMarker.setPaint(Color.orange);
        xMarker.setLabelFont(new Font("隶书",Font.BOLD,10));
        xMarker.setLabelAnchor(RectangleAnchor.BOTTOM_RIGHT);
        xMarker.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
        plot.addDomainMarker(xMarker);
        plot.setRangeGridlinePaint(Color.black);//设置X轴的颜色
        
        ValueAxis yAxis=plot.getRangeAxis();
        yAxis.setAutoRange(true);
        yAxis.setAutoRangeMinimumSize(50.0d);
        NumberAxis yNumber=(NumberAxis) plot.getRangeAxis();
        yNumber.setTickUnit(new NumberTickUnit(50d));
        yAxis.setLowerBound(50.0d);
        plot.setRangeAxis(yAxis);
        
        ValueAxis xAxis=plot.getDomainAxis();
        xAxis.setAutoRange(false);
        NumberAxis   numberaxis=(NumberAxis)plot.getDomainAxis();
        numberaxis.setTickUnit(new NumberTickUnit(0.1D));//设置X轴跨度每次增加1
        xAxis.setUpperBound(14.2d);
        xAxis.setLowerBound(11.8d);
        
        XYItemRenderer itRender=plot.getRenderer();
        
                try {
            PrintWriter  pw=new PrintWriter(out);
            StandardEntityCollection sec = new StandardEntityCollection();
            ChartRenderingInfo info = new ChartRenderingInfo(sec);

            filename=ServletUtilities.saveChartAsJPEG(chart,650, 400,null, session);
            ChartUtilities.writeImageMap(pw, filename,info, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return filename;
	}
	
	//最近7天的
	public String getFileName(HttpSession session ,JspWriter out){
		String filename=null;		
		// 在Mysql中使用 select  
        // year(accessdate),month(accessdate),day(accessdate),count(*)  
        // 其中accessdate 是一个date类型的时间  
        // 时间序列对象集合  
        TimeSeriesCollection chartTime = new TimeSeriesCollection();  
        // 时间序列对象，第1个参数表示时间序列的名字，第2个参数是时间类型，这里为天  
        // 该对象用于保存前count天每天的访问次数  
        TimeSeries timeSeries = new TimeSeries("日访问", Day.class);  
        // 为了演示，直接拼装数据  
        // Day的组装格式是day-month-year 访问次数  
        try {  
        	//从数据库查询数据
        	
        	timeSeries.add(new Day(1, 1, 2010), 50);  
            timeSeries.add(new Day(2, 1, 2010), 47);  
            timeSeries.add(new Day(3, 1, 2010), 82);  
            timeSeries.add(new Day(4, 1, 2010), 95);  
            timeSeries.add(new Day(5, 1, 2010), 104);  
            timeSeries.add(new Day(6, 1, 2010), 425);
        	  
            chartTime.addSeries(timeSeries);  
            XYDataset date = chartTime;  
            // 使用ChartFactory来创建时间序列的图表对象  
            JFreeChart chart = ChartFactory.createTimeSeriesChart(  
                    "网站每天访问统计", // 图形标题  
                    "日期", // X轴说明  
                    "访问量", // Y轴说明  
                    date, // 数据  
                    true, // 是否创建图例  
                    true, // 是否生成Tooltips  
                    false // 是否生产URL链接  
            );  
            // 设置整个图片的背景色  
            chart.setBackgroundPaint(Color.PINK);  
            // 设置图片有边框  
            chart.setBorderVisible(true);  
            // 获得图表区域对象  
            XYPlot xyPlot = (XYPlot) chart.getPlot();  
            // 设置报表区域的背景色  
            xyPlot.setBackgroundPaint(Color.lightGray);  
            // 设置横 纵坐标网格颜色  
            xyPlot.setDomainGridlinePaint(Color.GREEN);  
            xyPlot.setRangeGridlinePaint(Color.GREEN);  
            // 设置横、纵坐标交叉线是否显示  
            xyPlot.setDomainCrosshairVisible(true);  
            xyPlot.setRangeCrosshairVisible(true);  
            // 获得数据点（X,Y）的render，负责描绘数据点  
            XYItemRenderer xyItemRenderer = xyPlot.getRenderer();  
            if (xyItemRenderer instanceof XYLineAndShapeRenderer) {  
                XYLineAndShapeRenderer xyLineAndShapeRenderer = (XYLineAndShapeRenderer) xyItemRenderer;  
                xyLineAndShapeRenderer.setShapesVisible(true); // 数据点可见  
                xyLineAndShapeRenderer.setShapesFilled(true); // 数据点是实心点  
                xyLineAndShapeRenderer.setSeriesFillPaint(0, Color.RED); // 数据点填充为蓝色  
                xyLineAndShapeRenderer.setUseFillPaint(true);// 将设置好的属性应用到render上  
            }  
            // 配置以下内容方可解决乱码问题  
            // 配置字体  
            Font xfont = new Font("宋体", Font.PLAIN, 12);    // X轴  
            Font yfont = new Font("宋体", Font.PLAIN, 12);    // Y轴  
            Font kfont = new Font("宋体", Font.PLAIN, 12);    // 底部  
            Font titleFont = new Font("宋体", Font.BOLD, 25); // 图片标题  
            // 图片标题  
            chart.setTitle(new TextTitle(chart.getTitle().getText(), titleFont));  
            // 底部  
            chart.getLegend().setItemFont(kfont);             
            // X 轴  
            ValueAxis domainAxis = xyPlot.getDomainAxis();  
            domainAxis.setLabelFont(xfont);// 轴标题  
            domainAxis.setTickLabelFont(xfont);// 轴数值  
            domainAxis.setTickLabelPaint(Color.BLUE); // 字体颜色  
            // Y 轴  
            ValueAxis rangeAxis = xyPlot.getRangeAxis();  
            rangeAxis.setLabelFont(yfont);  
            rangeAxis.setLabelPaint(Color.BLUE); // 字体颜色  
            rangeAxis.setTickLabelFont(yfont);  
            // 定义坐标轴上日期显示的格式  
            DateAxis dateAxis = (DateAxis) xyPlot.getDomainAxis();  
            // 设置日期格式  
            dateAxis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));  
            // 向客户端输出生成的图片  
            PrintWriter  pw=new PrintWriter(out);
            StandardEntityCollection sec = new StandardEntityCollection();
            ChartRenderingInfo info = new ChartRenderingInfo(sec);
            filename=ServletUtilities.saveChartAsJPEG(chart,650, 400,null, session);
            ChartUtilities.writeImageMap(pw, filename,info, true);
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return filename;
    
	}
	
}



